package com.von.nhcf.controller;

import com.von.nhcf.api.MysqlRemoteService;
import com.von.nhcf.config.OSSProperties;
import com.von.nhcf.constant.NhcfConstant;
import com.von.nhcf.entity.vo.*;
import com.von.nhcf.util.OSSUtil;
import com.von.nhcf.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

@Controller
public class ProjectConsumerController {
    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MysqlRemoteService mysqlRemoteService;

    @RequestMapping("/show/project/details/{projectId}")
    public String showProjectDetail(@PathVariable("projectId") Integer projectId, ModelMap modelMap) {
            ResultEntity<DetailProjectVO> detailProjectVORemote = mysqlRemoteService.getDetailProjectVORemote(projectId);
            if (ResultEntity.getSUCCESS().equals(detailProjectVORemote.getResult())) {
                DetailProjectVO data = detailProjectVORemote.getData();
                modelMap.addAttribute(NhcfConstant.ATTR_NAME_DETAIL_PROJECT_VO, data);
            }
            return "project_detail";
    }

    @RequestMapping("/do/confirm/action")
    public String doConfirm(MemberConfirmInfoVO confirmInfoVO, HttpSession session, ModelMap modelMap) {
        // 从session中获取ProjectVO，并判断是否为空
        ProjectVO projectVO = (ProjectVO) session.getAttribute(NhcfConstant.ATTR_TEMP_PROJECT_VO);
        if (projectVO == null) {
            throw new RuntimeException("程序异常，ProjectVO不能为空");
        }
        // 设置确认信息
        projectVO.setMemberConfirmInfoVO(confirmInfoVO);
        // 从session域中获取当前登录用户信息
        MemberLoginVO loginVO = (MemberLoginVO) session.getAttribute(NhcfConstant.ATTR_NAME_MEMBER);
        Integer memberId = loginVO.getId();
        // 调用远程方法持久化ProjectVO
        ResultEntity<String> saveResult = mysqlRemoteService.saveProjectVORemote(projectVO, memberId);
        if (ResultEntity.getFAILURE().equals(saveResult.getResult())) {
            modelMap.addAttribute(NhcfConstant.ATTR_MESSAGE_NAME, saveResult.getMsg());
            return "project_confirm";
        }
        session.removeAttribute(NhcfConstant.ATTR_TEMP_PROJECT_VO);

        return "redirect:/project/to/success/page";
    }

    @RequestMapping("/save/return/info")
    @ResponseBody
    public ResultEntity<String> saveRetureInfo(ReturnVO returnVO, HttpSession session) {
        // 判断ProjectVO是否为空
        ProjectVO projectVO = (ProjectVO) session.getAttribute(NhcfConstant.ATTR_TEMP_PROJECT_VO);
        if (projectVO == null) {
            throw new RuntimeException("ProjectVO 不能为空！！！");
        }
        // 判断ProjectVO中的ReturnVOList是否存在
        List<ReturnVO> returnVOList = projectVO.getReturnVOList();
        if (returnVOList == null || returnVOList.size() == 0) {
            LinkedList<ReturnVO> returnVOS = new LinkedList<ReturnVO>();
            projectVO.setReturnVOList(returnVOS);
            returnVOList = returnVOS;
        }
        // 将前端传入的ReturnVO加入到ReturnVOList中
        returnVOList.add(returnVO);
        // 更新session中的ProjectVO
        session.setAttribute(NhcfConstant.ATTR_TEMP_PROJECT_VO, projectVO);

        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/upload/return/picture")
    @ResponseBody
    public ResultEntity<String> saveReturnPictureInfo(@RequestParam("returnPicture") MultipartFile file) throws IOException {
        return uploadOnePicture(file);
    }

    @RequestMapping("/save/project/info")
    public String saveProjectInfo(ProjectVO projectVO, MultipartFile headerPicture, List<MultipartFile> detailPictures,
                                  HttpSession session, ModelMap modelMap) throws IOException {
        // 上传头图到OSS
        if (!headerPicture.isEmpty()) {
            ResultEntity<String> uploadOSSResultEntity = uploadOnePicture(headerPicture);
            // 判断头图是否上传成功
            String result = uploadOSSResultEntity.getResult();
            if (ResultEntity.getSUCCESS().equals(result)) {
                // 将上传成功的头图在OSS中的访问地址添加到projectVO中
                projectVO.setHeaderPicturePath(uploadOSSResultEntity.getData());
            } else {
                session.setAttribute(NhcfConstant.ATTR_MESSAGE_NAME, NhcfConstant.MESSAGE_UPLOAD_HEADER_PICTURE_FAILURE);
                return "project_launch";
            }
        } else {
            session.setAttribute(NhcfConstant.ATTR_MESSAGE_NAME, NhcfConstant.MESSAGE_UPLOAD_HEADER_PICTURE_EMPTY);
            return "project_launch";
        }
        // 上传详情图片到OSS
        List<String> uploadSuccessfulDetailPicturePaths = new LinkedList<>();
        if (detailPictures != null && detailPictures.size() != 0) {
            // 遍历详情图片list，依次上传图片
            for (MultipartFile detailPicture : detailPictures) {
                if (detailPicture == null || detailPicture.isEmpty()) {
                    session.setAttribute(NhcfConstant.ATTR_MESSAGE_NAME, NhcfConstant.MESSAGE_UPLOAD_DETAIL_PICTURE_ZERO);
                    return "project_launch";
                }
                ResultEntity<String> uploadPictureResult = uploadOnePicture(detailPicture);
                if (ResultEntity.getSUCCESS().equals(uploadPictureResult.getResult())) {
                    uploadSuccessfulDetailPicturePaths.add(uploadPictureResult.getData());
                } else {
                    session.setAttribute(NhcfConstant.ATTR_MESSAGE_NAME, NhcfConstant.MESSAGE_UPLOAD_DETAIL_PICTURE_FAILURE);
                    return "project_launch";
                }
            }
            projectVO.setDetailPicturePathList(uploadSuccessfulDetailPicturePaths);
        } else {
            session.setAttribute(NhcfConstant.ATTR_MESSAGE_NAME, NhcfConstant.MESSAGE_UPLOAD_DETAIL_PICTURE_EMPTY);
            return "project_launch";
        }
        // projectVO加入到session域中
        session.setAttribute(NhcfConstant.ATTR_TEMP_PROJECT_VO, projectVO);

        return "redirect:/project/to/return/info/page";
    }

    public ResultEntity<String> uploadOnePicture(MultipartFile picture) throws IOException {
        if (!picture.isEmpty()) {
            ResultEntity<String> uploadOSSResultEntity = OSSUtil.uploadFileToOss(ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    picture.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    picture.getOriginalFilename());
            return uploadOSSResultEntity;
        } else {
            return ResultEntity.failureWithMsg("图片不能为空！！！");
        }
    }
}
